#include"../../source/server.hpp"


void Close(Channel* channel)
{

      channel->Remove();
      delete channel;
}
void Read(Channel* channel)
{
      char buffer[1024]={0};
      int n=read(channel->GetFd(),buffer,1023);
      std::cout<<"read"<<std::endl;
      if(n<=0)
      {
            Close(channel);
            return;
      }
      DBG_LOG("%s",buffer);
      channel->EnableWrite();//启动可写事件
      std::cout<<"get a new message:"<<buffer<<std::endl;
}
void Write(Channel* channel)
{
      const char* s="I received a message....";
      int n=write(channel->GetFd(),s,strlen(s));
      if(n<=0)
      {
            Close(channel);
      }
      channel->DisableWrite();
}
void Event(Channel* channel,uint64_t timerid,EventLoop* loop)
{
      loop->TimerRefresh(timerid);
      std::cout<<"有了一个事件"<<std::endl;
}

void Error(Channel* channel)
{
      Close(channel);
}
void Accept(EventLoop* loop,Channel* channel)
{
      int listen_fd=channel->GetFd();
      struct sockaddr_in addr;
      socklen_t len;
      int newfd=accept(listen_fd,(sockaddr*)&addr,&len);
      if(newfd<=0)
      {
            std::cout<<"accept error"<<std::endl;
            return;
      }
      uint64_t timerid=rand()%10000;
      Channel* new_channel=new Channel(newfd,loop);//？：这个对象出作用域之后就消散了
      new_channel->SetReadCallback(std::bind(Read,new_channel));
      new_channel->SetWriteCallback(std::bind(Write,new_channel));
      new_channel->SetEventCallback(std::bind(Event,new_channel,timerid,loop));
      new_channel->SetCloseCallback(std::bind(Close,new_channel));
      new_channel->SetErrorCallback(std::bind(Error,new_channel));

      loop->TimerAdd(timerid,10,std::bind(Close,channel));
      new_channel->EnableRead();
}

int main()
{
      srand(time(nullptr));
      Socket sock;
      sock.Sock();
      sock.CreateServer(9999);
      std::cout<<"listensock:"<<sock.GetFd()<<std::endl;
      
      EventLoop loop;
      Channel channel(sock.GetFd(),&loop);
      channel.SetReadCallback(std::bind(Accept,&loop,&channel));
      channel.EnableRead();
      //std::cout<<"ehhhhh"<<std::endl;
      loop.Start();
      return 0;
}